// convert函数， 将数组转为树

interface IArrayItem {
  id: number;
  name: string;
  parentId: number;
}

interface ITreeNode {
  id: number;
  name: string;
  children?: ITreeNode[];
}

function convert(arr: IArrayItem[]):ITreeNode | null {
  const idToTreeNode: Map<number, ITreeNode> = new Map();

  let root
  arr.forEach(item => {
    const {id, name, parentId} = item
    const treeNode: ITreeNode = {id, name}
    idToTreeNode.set(id, treeNode)

    const parentNode = idToTreeNode.get(parentId)
    if (parentNode) {
      if(parentNode.children == null) parentNode.children = []
      parentNode.children.push(treeNode)
    }

    if(parentId === 0)  root = treeNode
  })
  return root
}

const arr = [
  {id: 1, name: 'partA', parentId: 0},
  {id: 2, name: 'partB', parentId: 1},
  {id: 3, name: 'partC', parentId: 1},
  {id: 4, name: 'partD', parentId: 2},
  {id: 5, name: 'partE', parentId: 2},
  {id: 6, name: 'partF', parentId: 3}
]

// 思路
// 遍历数组， 生成tree node
// 找到parentNode， 并加入它的children 

// 如何找到parentNode
// Map